<template>
  <el-table
    ref="tableRef"
    :data="tableData"
    :height="autoHeight ? tableHeight : undefined"
    :highlight-current-row="singleSelect"
    class="base-table"
    :tooltip-options="{
      popperOptions: {
        strategy: 'absolute',
      },
    }"
    v-bind="$attrs"
  >
    <BaseTableColumn
      v-for="(column, columnIndex) in tableColumns"
      :key="column.prop ? column.prop + columnIndex : columnIndex"
      :column="column"
      :pageInfo="paginationData"
    >
      <template v-for="slot in Object.keys($slots)" #[slot]="scope">
        <slot :name="slot" v-bind="scope" />
      </template>
    </BaseTableColumn>
  </el-table>
</template>

<script lang="ts" setup>
import BaseTableColumn from '@/components/base/BaseTableColumn.vue';

import { onBeforeUnmount, onMounted, ref, unref, useAttrs, useSlots } from 'vue';

const tableRef = ref(null);
const props = defineProps({
  tableColumns: {
    type: Object,
    default: () => [],
  },
  tableData: {
    type: Array,
    default: () => [],
  },
  paginationData: {
    type: Object,
    default: () => ({
      pageNum: 1,
      pageSize: 10,
      total: 0,
    }),
  },
  autoHeight: {
    type: Boolean,
    default: true,
  },
  singleSelect: {
    type: Boolean,
    default: false,
  },
});

const attrs = useAttrs();

const slots = useSlots();

const tableHeight = ref(0);
const initTableHeight = () => {
  const resizeObserver = new ResizeObserver((entries) => {
    const { height } = entries.shift()?.contentRect;
    tableHeight.value = height;
    unref(tableRef).scrollBarRef.update();
  });
  onMounted(() => {
    resizeObserver.observe(unref(tableRef).$el.parentElement);
  });
  onBeforeUnmount(() => {
    resizeObserver.disconnect();
  });
};
props.autoHeight && initTableHeight();

// 单选
const setSingleSelect = (row) => {
  unref(tableRef).setCurrentRow(row);
};

defineExpose({
  tableRef,
  setSingleSelect,
});
</script>

<style lang="less" scoped>
.base-table {
  --el-table-header-bg-color: #f8f8f9;
  :deep(.el-table__empty-text:has(> .base-empty)) {
    line-height: unset;
    width: 100%;
    height: 100%;
  }
}
</style>
